package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import com.sddnytsh.body_buildingsystem.utils.DateUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 二级楼中楼抽屉组件
 */
@Composable
fun NestedReplyDrawer(
    isVisible: Boolean,
    rootComment: Comment,
    onDismiss: () -> Unit,
    onReplySent: () -> Unit,
    modifier: Modifier = Modifier
) {
    if (!isVisible) return

    var replies by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var showLoadMore by remember { mutableStateOf(false) }
    var currentPage by remember { mutableStateOf(1) }
    var replyText by remember { mutableStateOf("") }
    var isSubmitting by remember { mutableStateOf(false) }
    
    val communityApiService = remember { CommunityApiService() }
    val scope = rememberCoroutineScope()
    val currentUser = UserState.currentUser

    // 加载二级回复
    LaunchedEffect(rootComment.id) {
        isLoading = true
        try {
            val result = communityApiService.getReplies(rootComment.id, 1, 3)
            result.onSuccess { data ->
                val replyList = data["replies"] as? List<Map<String, Any>> ?: emptyList()
                replies = replyList.map { replyData ->
                    Comment(
                        id = (replyData["id"] as? Number)?.toLong() ?: 0L,
                        postId = (replyData["postId"] as? Number)?.toLong() ?: 0L,
                        userId = (replyData["userId"] as? Number)?.toLong() ?: 0L,
                        content = replyData["content"] as? String ?: "",
                        likeCount = (replyData["likeCount"] as? Number)?.toInt() ?: 0,
                        isLiked = replyData["isLiked"] as? Boolean ?: false,
                        createdAt = replyData["createdAt"] as? String ?: "",
                        author = replyData["author"] as? String,
                        parentId = (replyData["parentId"] as? Number)?.toLong(),
                        rootId = (replyData["rootId"] as? Number)?.toLong(),
                        isDeleted = replyData["isDeleted"] as? Boolean ?: false
                    )
                }
                showLoadMore = (data["total"] as? Number)?.toInt() ?: 0 > 3
            }
        } catch (e: Exception) {
            // 处理错误
        } finally {
            isLoading = false
        }
    }

    // 抽屉内容
    Card(
        modifier = modifier
            .fillMaxWidth()
            .height(400.dp)
            .padding(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
        shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            // 抽屉头部
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "回复 ${rootComment.author ?: "匿名用户"}",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary
                )
                IconButton(onClick = onDismiss) {
                    Icon(
                        imageVector = Icons.Default.Close,
                        contentDescription = "关闭",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 回复输入框
            OutlinedTextField(
                value = replyText,
                onValueChange = { replyText = it },
                modifier = Modifier.fillMaxWidth(),
                placeholder = { Text("回复 ${rootComment.author ?: "匿名用户"}...") },
                maxLines = 2,
                enabled = !isSubmitting,
                keyboardOptions = KeyboardOptions(
                    capitalization = KeyboardCapitalization.Sentences,
                    imeAction = ImeAction.Send
                ),
                trailingIcon = {
                    IconButton(
                        onClick = {
                            android.util.Log.d("NestedReplyDrawer", "[sendReply] clicked")
                            android.util.Log.d("NestedReplyDrawer", "[sendReply] params: postId=${rootComment.postId}, parentId=${rootComment.id}, rootId=${rootComment.rootId ?: rootComment.id}, content=${replyText.trim()}")
                            
                            if (replyText.trim().isNotEmpty() && currentUser != null) {
                                android.util.Log.d("NestedReplyDrawer", "[sendReply] starting request")
                                scope.launch {
                                    isSubmitting = true
                                    try {
                                        val result = communityApiService.createReply(
                                            postId = rootComment.postId,
                                            parentId = rootComment.id,
                                            rootId = rootComment.rootId ?: rootComment.id,
                                            content = replyText.trim()
                                        )
                                        android.util.Log.d("NestedReplyDrawer", "[sendReply] result received: ${result.isSuccess}")
                                        result.onSuccess { comment ->
                                            android.util.Log.d("NestedReplyDrawer", "[sendReply] success callback: comment=$comment")
                                            replyText = ""
                                            onReplySent()
                                            // 重新加载回复列表
                                            val reloadResult = communityApiService.getReplies(rootComment.id, 1, 3)
                                            reloadResult.onSuccess { data ->
                                                android.util.Log.d("NestedReplyDrawer", "[sendReply] reload success: data=$data")
                                                val replyList = data["replies"] as? List<Map<String, Any>> ?: emptyList()
                                                replies = replyList.map { replyData ->
                                                    Comment(
                                                        id = (replyData["id"] as? Number)?.toLong() ?: 0L,
                                                        postId = (replyData["postId"] as? Number)?.toLong() ?: 0L,
                                                        userId = (replyData["userId"] as? Number)?.toLong() ?: 0L,
                                                        content = replyData["content"] as? String ?: "",
                                                        likeCount = (replyData["likeCount"] as? Number)?.toInt() ?: 0,
                                                        isLiked = replyData["isLiked"] as? Boolean ?: false,
                                                        createdAt = replyData["createdAt"] as? String ?: "",
                                                        author = replyData["author"] as? String,
                                                        parentId = (replyData["parentId"] as? Number)?.toLong(),
                                                        rootId = (replyData["rootId"] as? Number)?.toLong(),
                                                        isDeleted = replyData["isDeleted"] as? Boolean ?: false
                                                    )
                                                }
                                                android.util.Log.d("NestedReplyDrawer", "[sendReply] UI updated: replies count=${replies.size}")
                                            }
                                            reloadResult.onFailure { error ->
                                                android.util.Log.e("NestedReplyDrawer", "[sendReply] reload failed", error)
                                            }
                                        }
                                        result.onFailure { error ->
                                            android.util.Log.e("NestedReplyDrawer", "[sendReply] request failed", error)
                                        }
                                    } catch (e: Exception) {
                                        // 处理错误
                                        android.util.Log.e("NestedReplyDrawer", "[sendReply] exception", e)
                                        e.printStackTrace()
                                    } finally {
                                        isSubmitting = false
                                        android.util.Log.d("NestedReplyDrawer", "[sendReply] finished")
                                    }
                                }
                            } else {
                                android.util.Log.w("NestedReplyDrawer", "[sendReply] conditions not met: replyText=${replyText.trim()}, currentUser=$currentUser")
                            }
                        },
                        enabled = replyText.trim().isNotEmpty() && !isSubmitting
                    ) {
                        Icon(
                            imageVector = Icons.Default.Send,
                            contentDescription = "发送",
                            tint = if (replyText.trim().isNotEmpty()) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 回复列表
            if (isLoading) {
                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else if (replies.isEmpty()) {
                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无回复",
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        fontSize = 14.sp
                    )
                }
            } else {
                LazyColumn(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    items(replies) { reply ->
                        ReplyItem(
                            reply = reply,
                            onLikeClick = { replyId ->
                                // 处理点赞
                            },
                            onReplyClick = { replyComment ->
                                replyText = "@${replyComment.author ?: "匿名用户"} "
                            }
                        )
                    }
                    
                    if (showLoadMore) {
                        item {
                            LoadMoreButton(
                                onClick = {
                                    scope.launch {
                                        currentPage++
                                        try {
                                            val result = communityApiService.getReplies(rootComment.id, currentPage, 10)
                                            result.onSuccess { data ->
                                                val replyList = data["replies"] as? List<Map<String, Any>> ?: emptyList()
                                                val newReplies = replyList.map { replyData ->
                                                    Comment(
                                                        id = (replyData["id"] as? Number)?.toLong() ?: 0L,
                                                        postId = (replyData["postId"] as? Number)?.toLong() ?: 0L,
                                                        userId = (replyData["userId"] as? Number)?.toLong() ?: 0L,
                                                        content = replyData["content"] as? String ?: "",
                                                        likeCount = (replyData["likeCount"] as? Number)?.toInt() ?: 0,
                                                        isLiked = replyData["isLiked"] as? Boolean ?: false,
                                                        createdAt = replyData["createdAt"] as? String ?: "",
                                                        author = replyData["author"] as? String,
                                                        parentId = (replyData["parentId"] as? Number)?.toLong(),
                                                        rootId = (replyData["rootId"] as? Number)?.toLong(),
                                                        isDeleted = replyData["isDeleted"] as? Boolean ?: false
                                                    )
                                                }
                                                replies = replies + newReplies
                                                showLoadMore = (data["hasMore"] as? Boolean) ?: false
                                            }
                                        } catch (e: Exception) {
                                            // 处理错误
                                        }
                                    }
                                }
                            )
                        }
                    }
                }
            }
        }
    }
}

/**
 * 回复项组件
 */
@Composable
fun ReplyItem(
    reply: Comment,
    onLikeClick: (Long) -> Unit,
    onReplyClick: (Comment) -> Unit,
    modifier: Modifier = Modifier
) {
    val currentUser = UserState.currentUser
    val isCurrentUser = currentUser?.id == reply.userId
    
    Card(
        modifier = modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
        )
    ) {
        Column(
            modifier = Modifier.padding(8.dp)
        ) {
            // 回复头部
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        modifier = Modifier
                            .size(24.dp)
                            .clip(CircleShape)
                            .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.1f)),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = (reply.author?.firstOrNull() ?: "?").toString(),
                            color = MaterialTheme.colorScheme.primary,
                            fontWeight = FontWeight.Bold,
                            fontSize = 10.sp
                        )
                    }
                    
                    Spacer(modifier = Modifier.width(6.dp))
                    
                    Text(
                        text = reply.author ?: "匿名用户",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                    Spacer(modifier = Modifier.width(6.dp))
                    
                    Text(
                        text = DateUtils.formatDate(reply.createdAt),
                        fontSize = 10.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                // 删除按钮（仅当前用户可见）
                if (isCurrentUser) {
                    TextButton(
                        onClick = { /* TODO: 实现删除 */ },
                        colors = ButtonDefaults.textButtonColors(
                            contentColor = MaterialTheme.colorScheme.error
                        )
                    ) {
                        Text("删除", fontSize = 10.sp)
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 回复内容
            if (reply.isDeleted) {
                Text(
                    text = "该回复已被删除",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        fontStyle = androidx.compose.ui.text.font.FontStyle.Italic
                    )
                )
            } else {
                Text(
                    text = reply.content,
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurface,
                    lineHeight = 16.sp,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis
                )
            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 操作按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 点赞按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { onLikeClick(reply.id) }
                ) {
                    Icon(
                        imageVector = if (reply.isLiked) Icons.Filled.ThumbUp else Icons.Default.ThumbUpOffAlt,
                        contentDescription = "点赞",
                        tint = if (reply.isLiked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(14.dp)
                    )
                    Spacer(modifier = Modifier.width(3.dp))
                    Text(
                        text = reply.likeCount.toString(),
                        fontSize = 10.sp,
                        color = if (reply.isLiked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                // 回复按钮
                TextButton(
                    onClick = { onReplyClick(reply) },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.primary
                    )
                ) {
                    Text("回复", fontSize = 10.sp)
                }
            }
        }
    }
}

/**
 * 加载更多按钮
 */
@Composable
fun LoadMoreButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable { onClick() },
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
        )
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "查看更多回复",
                fontSize = 12.sp,
                color = MaterialTheme.colorScheme.primary,
                fontWeight = FontWeight.Medium
            )
        }
    }
}
